<template>
  <div>
    <h2>图表</h2>
    <div class="chart" id="oneChart">图表的容器1</div>
  </div>
</template>

<script>
import { inject, onMounted, reactive } from "vue";
export default {
  setup() {
    let $echarts = inject("echarts");
    let $http = inject("axios");

    let data = reactive({});
    let xdata = reactive([]);
    let ydata = reactive([]);
    // 数据处理
    function setData() {
      xdata = data.data.chartData.chartData.map((v) => v.title);
      ydata = data.data.chartData.chartData.map((v) => v.num);
      console.log(xdata);
      console.log(ydata);
    }
    async function getState() {
      data = await $http({ url: "/one/data" });
      // console.log(data.data.chartData);
    }

    onMounted(() => {
      let myChart = $echarts.init(document.getElementById("oneChart"));

      // 调用请求
      // .then 异步调用，要等数据先请求回来，才能进行数据处理
      getState().then(() => {
        setData();

        myChart.setOption({
          grid: {
            top: "9%",
            left: "1%",
            right: "6%",
            bottom: "1%",
            containLabel: true,
          },
          xAxis: {
            type: "value",
            axisLine: {
              lineStyle: {
                color: "#fff",
              },
            },
          },
          yAxis: {
            type: "category",
            data: xdata,
            axisLine: {
              lineStyle: {
                color: "#fff",
              },
            },
          },
          series: [
            {
              data: ydata,
              type: "bar",
              itemStyle: {
                normal: {
                  barBorderRadius: [0, 20, 20, 0],
                  color: new $echarts.graphic.LinearGradient(0, 0, 1, 0, [
                    {
                      offset: 0,
                      color: "#005eaa",
                    },
                    {
                      offset: 0.5,
                      color: "#339ca8",
                    },
                    {
                      offset: 1,
                      color: "#cda819",
                    },
                  ]),
                },
              },
            },
          ],
        });
      });
    });
    return {
      getState,
      setData,
    };
  },
};
</script>

<style lang="less" scoped>
.chart {
  height: 360px;
}
h2 {
  height: 10px;
  color: #fff;
  line-height: 48px;
  font-size: 15px;
  text-align: center;
}
</style>
